package com.info.zhiduoduo.core.service.payment.project;

import com.info.zhiduoduo.common.configs.CommonConfig;
import com.info.zhiduoduo.common.configs.KltPayConfig;
import com.info.zhiduoduo.common.configs.PayConfig;
import com.info.zhiduoduo.common.configs.ZddUrlConfig;
import com.info.zhiduoduo.common.constants.company.CompanyAccountFlowBizType;
import com.info.zhiduoduo.common.constants.project.CompanyProjectState;
import com.info.zhiduoduo.common.exception.RollbackException;
import com.info.zhiduoduo.common.utils.StringUtil;
import com.info.zhiduoduo.core.service.CoreBrokerageService;
import com.info.zhiduoduo.core.service.CoreCompanyService;
import com.info.zhiduoduo.core.service.CoreInvoiceService;
import com.info.zhiduoduo.core.service.CoreProjectService;
import com.info.zhiduoduo.core.service.DingdingNoticeService;
import com.info.zhiduoduo.core.service.WxCrowdsourceMessageService;
import com.info.zhiduoduo.core.service.WxMessageService;
import com.info.zhiduoduo.core.service.WxPartnerMessageService;
import com.info.zhiduoduo.core.service.ZhiduoduoProjectService;
import com.info.zhiduoduo.core.service.impl.CeoNoticeService;
import com.info.zhiduoduo.repository.dto.maker.MakerDetailDto;
import com.info.zhiduoduo.repository.entity.company.CompanyAccountflow;
import com.info.zhiduoduo.repository.entity.company.CompanyPayment;
import com.info.zhiduoduo.repository.entity.company.CompanyProject;
import com.info.zhiduoduo.repository.entity.order.TradeRecord;
import com.info.zhiduoduo.repository.mapper.company.CompanyAccountMapper;
import com.info.zhiduoduo.repository.mapper.company.CompanyProjectMapper;
import com.info.zhiduoduo.repository.mapper.crowdsource.CrowdsourceAccountMapper;
import com.info.zhiduoduo.repository.mapper.crowdsource.CrowdsourceProjectItemMapper;
import com.info.zhiduoduo.repository.mapper.crowdsource.CrowdsourceProjectMapper;
import com.info.zhiduoduo.repository.mapper.maker.MakerMapper;
import com.info.zhiduoduo.repository.mapper.maker.MakerStudioMapper;
import com.info.zhiduoduo.repository.mapper.partner.PartnerBrokerageMapper;
import com.info.zhiduoduo.repository.mapper.partner.PartnerCompanyMapper;
import com.info.zhiduoduo.repository.mapper.partner.PartnerMapper;
import com.info.zhiduoduo.repository.mapper.partner.PartnerSubMapper;
import com.info.zhiduoduo.repository.mapper.system.ProjectCategoryMapper;
import com.info.zhiduoduo.repository.mapper.taxer.TaxerInvoiceMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@Transactional
public class BaseProjectJiugePaymentService extends BaseProjectPaymentService {

	@Autowired
	MakerMapper makerMapper;
	@Autowired
	PartnerCompanyMapper partnerCompanyMapper;
	@Autowired
	PartnerBrokerageMapper partnerBrokerageMapper;
	@Autowired
	ProjectCategoryMapper projectCategoryMapper;
	@Autowired
	CompanyProjectMapper projectMapper;
	@Autowired
	CrowdsourceAccountMapper crowdsourceAccountMapper;
	@Autowired
	CrowdsourceProjectItemMapper crowdsourceProjectItemMapper;
	@Autowired
	CrowdsourceProjectMapper crowdsourceProjectMapper;
	@Autowired
	MakerStudioMapper makerStudioMapper;
	@Autowired
	TaxerInvoiceMapper taxerInvoiceMapper;
	@Autowired
	PartnerSubMapper partnerSubMapper;
	@Autowired
	PartnerMapper partnerMapper;
	@Resource
	CompanyAccountMapper companyAccountMapper;

	@Autowired
	CoreCompanyService coreCompanyService;
	@Autowired
	DingdingNoticeService dingdingNoticeService;
	@Autowired
	WxMessageService wxMessageService;
	@Autowired
	WxPartnerMessageService wxPartnerMessageService;
	@Autowired
	WxCrowdsourceMessageService wxCrowdsourceMessageService;
	@Autowired
	CeoNoticeService ceoNoticeService;
	@Autowired
	CoreProjectService coreProjectService;
	@Autowired
	ZhiduoduoProjectService zhiduoduoProjectService;
	@Autowired
	CoreBrokerageService coreBrokerageService;
	@Autowired
	CoreInvoiceService coreInvoiceService;

	@Autowired
	CommonConfig commonConfig;
	@Autowired
	ZddUrlConfig zddUrlConfig;
	@Autowired
	PayConfig payConfig;
	@Autowired
	KltPayConfig kltPayConfig;

	@Override
	public void deductCompanyBalanceForPublishProject(CompanyPayment companyPayment, CompanyProject project) {
		int compid = project.getCompid();
		BigDecimal projectdealamount = project.getProjectdealamount();

		// 修改企业余额
		BigDecimal beforeBalance = companyPayment.getBalance();
		BigDecimal currBalance = companyPayment.getBalance().subtract(projectdealamount);
		companyPayment.setBalance(currBalance).updateById();

		//生成企业流水
		String username = "";
		MakerDetailDto userInfo = makerMapper.getUserDetail(project.getUserid());
		if (userInfo != null) {
			username = StringUtil.isEmpty(userInfo.getUsername()) ? userInfo.getRealname() : userInfo.getUsername();
		}
		CompanyAccountflow accountflow = new CompanyAccountflow().setCompid(compid)
				.setFlowname(project.getProjectname() + "项目付款给创客" + username)
				.setFlowtype(2)
				.setBizid(project.getProjectid())
				.setBizType(CompanyAccountFlowBizType.ZDD_PROJECT)
				.setPayId(project.getPayId())
				.setFlowAmount(projectdealamount)
				.setBeforeBalance(beforeBalance)
				.setCurrBalance(currBalance)
				.setBeforeFrozenBalance(companyPayment.getFrozenBalance())
				.setCurrFrozenBalance(companyPayment.getFrozenBalance());

		if (accountflow.insert()) {
			return;
		}
		//如果执行到这里了,说明前面有数据库插入或更新报错,需要回滚
		log.info("发布项目,处理扣除企业余额失败,需要回滚");
		throw new RollbackException("发布项目失败");
	}

	/**
	 * 项目款项在第三方支付公司的代付交易成功后，处理后续的业务,企业订单状态修改，产生创客账户流水。
	 *
	 * @param trade
	 */
	@Override
	public void doAfterPayUserTradeSucceed(CompanyProject project, TradeRecord trade) {
		if (project != null) {
			project.setState(CompanyProjectState.COMPLETED).setProjectfinish(new Date()).updateById();

			try {
				int tradeid = 0;
				String tradeno = "";
				if (trade != null) {
					tradeid = trade.getTradeid();
					tradeno = trade.getTradeno();
				}

				zhiduoduoProjectService.handleCompanyOrderAfter(project);
				zhiduoduoProjectService.handleUserProjectAccountFlow(project, tradeid);
				coreBrokerageService.handleZhiduoduoProjectPartnerBrokerage(project, tradeid, tradeno);
				coreInvoiceService.createZhiduoduoProjectInvoice(project.getProjectid());
			} catch (Exception e) {
				//报错,回滚
				log.error("doAfterTradeSucceed 报错:", e);
				throw new RollbackException("处理创客流水和合伙人佣金失败");
			}
		}
	}
}
